#!/bin/bash

if [ -z "$1" ] || [ ! -e "$1" ]; then
    echo "Usages: $0 <android_sdk_dir>";
    exit 0;
fi

working_dir=`pwd`

# 移除可能存在的冲突文件
rm -rf $working_dir/EC200A-Kernel.patch

# 打 Kernel 补丁
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/EC200A-Kernel.patch -o $working_dir/EC200A-Kernel.patch
patch -p1 -N -d $1/kernel < $working_dir/EC200A-Kernel.patch
rm -rf $working_dir/EC200A-Kernel.patch

# 打 Android 补丁
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/EC200A-Android.patch -o $working_dir/EC200A-Android.patch
tmp_key="tmp_splits_"`date +%s`
cat $working_dir/EC200A-Android.patch | csplit -qf '' -b $tmp_key".%d.diff" - '/^project.*\/$/' '{*}'
for proj_diff in `ls $tmp_key.*.diff`
do 
    chg_dir="$1/"`cat $proj_diff | grep '^project.*\/$' | cut -d " " -f 2`
    echo "Now Patching: $chg_dir"
    if [ -e $chg_dir ]; then
        ( cd $chg_dir; \
            cat $working_dir/$proj_diff | grep -v '^project.*\/$' | patch -Np1;);
    else
        echo "$0: Project directory $chg_dir don't exists.";
    fi
done
rm -fr $tmp_key*
rm -rf $working_dir/EC200A-Android.patch

# 下载bin和lib文件
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/lib/libreference-ril-EC200-v7a.so -o $1/vendor/rockchip/common/phone/lib/libreference-ril-EC200-v7a.so
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/lib/libreference-ril-EC200-v8a.so -o $1/vendor/rockchip/common/phone/lib/libreference-ril-EC200-v8a.so
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/bin/iperf -o $1/vendor/rockchip/common/phone/bin/iperf
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/bin/mpstat -o $1/vendor/rockchip/common/phone/bin/mpstat
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/bin/QAndroidLog -o $1/vendor/rockchip/common/phone/bin/QAndroidLog
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/bin/QFirehose -o $1/vendor/rockchip/common/phone/bin/QFirehose
curl -fsSL https://gitee.com/fengmoxi/TSPI_Patch/raw/master/LTE/EC200A/conf/ql-ril.conf -o $1/vendor/rockchip/common/phone/etc/ql-ril.conf
